﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
using RoketSolutions.SP2010.Infrostructure.UI.WebParts;
using RoketSolutions.SP2010.SecurityTrimming.Helpers;
using RoketSolutions.SP2010.SecurityTrimming.SecurityTrimming;
using RoketSolutions.SP2010.SecurityTrimming.SecurityTrimming.Interfaces;
using RoketSolutions.SP2010.SecurityTrimming.WebParts.ToolParts;
using RoketSolutions.SP2010.Infrostructure.Common.Extensions;
using WebPart = System.Web.UI.WebControls.WebParts.WebPart;

namespace RoketSolutions.SP2010.SecurityTrimming.WebParts.SecurityTrimming
{
    [ToolboxItemAttribute(false)]
    public class SecurityTrimming : LocalizableWebPart
    {
        public SecurityTrimming() : this(new DefaultTrimmingStrategy())
        {
            ExportMode = WebPartExportMode.All;
            ChromeType = PartChromeType.None;
        }

        public SecurityTrimming(ITrimmingStrategy trimmingStrategy)
        {
            TrimmingStrategy = trimmingStrategy;
        }

        #region / Properties /

        TrimmingSettings _settings;

        [WebBrowsable(false)]
        [Personalizable(PersonalizationScope.Shared)]
        public TrimmingSettings Settings
        {
            get
            {
                if (_settings == null || _settings.Count() == 0)
                    _settings = RetrieveSettings();
                return _settings;
            }
            set
            {
                _settings = value;
            }
        }

        public ITrimmingStrategy TrimmingStrategy { get; set; }

        protected override string ResourcesFolderPath
        {
            get { return string.Empty; }
        }

        #endregion

        #region / Overriden Methods /

        [ConnectionConsumer("Trimming Strategy", AllowsMultipleConnections = false)]
        public void TrimmingStrategyConnectionPoint(ITrimmingStrategy strategy)
        {
            TrimmingStrategy = strategy;
        }

        public override ToolPart[] GetToolParts()
        {
            var tools = new List<ToolPart>();

            tools.Add(new SecurityTrimmingToolPart(Settings));
            tools.AddRange(base.GetToolParts());

            return tools.ToArray();
        }

        protected override void OnPreRender(EventArgs e)
        {
            ProcessTrimming();
            base.OnPreRender(e);
        }

        #endregion

        #region / Helper Methods /

        protected  virtual void ProcessTrimming()
        {
            if (!IsEditMode && TrimmingStrategy != null)
            {
                TrimmingStrategy.Init(SPContext.Current.Web.CurrentUser, Settings);

                var enumerator = new ControlEnumerator(Page);
                enumerator.Enumerate<WebPart>(
                    webpart =>
                        {
                            webpart.Hidden = !TrimmingStrategy.CheckWebPartAccessibility(webpart);
                        });
            }
        }

        private TrimmingSettings RetrieveSettings()
        {
            var settings = new TrimmingSettings();
            var enumerator = new ControlEnumerator(Page);

            enumerator.Enumerate<WebPart>(
                webpart=>
                    {
                        if (!webpart.Title.IsNullOrEmpty() && webpart.GetType() != typeof(SecurityTrimming))
                        {
                            settings.Add(new SettingDefinition
                                             {
                                                 ControlId = webpart.UniqueID,
                                                 ControlTitle = webpart.Title
                                             });
                        }
                    });

            return settings;
        }

        #endregion

    }
}
